﻿using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Elderos.Utils
{
    public static class TextUtils
    {
        public static bool IsCorrectLeftPosition(this string text, int start)
        {
            return start == 0 || !Char.IsLetterOrDigit(text[start - 1]);
        }

        public static bool IsCorrectRightPosition(this string text, int nextIx)
        {
            if (nextIx > text.Length) return false;
            return nextIx == text.Length || !Char.IsLetterOrDigit(text[nextIx]);
        }



        public static Token GetNextWord(this string text, int last)
        {
            int start = last + 1;
            for (; start < text.Length; start++)
            {
                if (IsCorrectLeftPosition(text, start)) break;
            }
            if (start >= text.Length) return null;

            int len = 0;
            for (; start + len <= text.Length; len++)
            {
                if (IsCorrectRightPosition(text, start + len)) break;
            }

            if (len < 1) return null;

            string result = text.Substring(start, len);
            return new Token(result, start);
        }

        public static Token GetPreviousWord(this string text, int first)
        {
            int last = first - 1;
            for (; last > 0; last--)
            {
                if (IsCorrectRightPosition(text, last + 1)) break;
            }
            if (last <= 0) return null;

            int start = last;
            for (; start >= 0; start--)
            {
                if (IsCorrectLeftPosition(text, start)) break;
            }

            if (start < 0) return null;

            int len = last - start + 1;

            string result = text.Substring(start, len);
            return new Token(result, start);
        }
    }
}
